<?php
/**
 * Created by PhpStorm.
 * User: ml
 * Date: 2017-11-30
 * Time: 15:49
 */

class Safety extends MY_Controller
{
    function __construct()
    {
        parent::__construct();
        //需要加载Model;
        $this->load->model('M_train_flow');
    }
    //【列车流水表t_train_flow 列车流水日志表 t_train_flow_log（可自行添加所需字段）】
    //
    //
    //
    //
    /**
     * 获取左侧列车流水（可以搜索车次暂停）
     */
    public function getTrainFlow(){
        /*
         1:接发车作业安全控制图起始时间为当天0点到第二天0点
         2:允许查看之前时间天的列车流水（做成分页形式，上面给出前一天、当天时间戳、后一天，下面是列车流水信息）
         3:输入车次可以查询该车次信息（只显示查询车次，同作用于前一天、后一天）
         */

        //传三个参数 当前时间  前后翻页参数 查询车次
        //默认当天列车流水
        $now_time = getParam($this->input->get_post("time", true), 'string' ,'');//当前页面时间 格式 20171212
        $last_next = getParam($this->input->get_post("page", true), 'string' ,'');//前后翻页参数 参数1：last 2：next
        $train_name = getParam($this->input->get_post("name", true), 'string' ,'');//查询车次 例：K6666
        $where ="";//默认where条件
        $time = time();
        $flows = "";
        if(!empty($train_name) && $now_time!='')
        {
            $where .= "AND f.train_number='$train_name'";

            $time =strtotime($now_time);
        }
        else
        {
            if($now_time!='' && $last_next!='')
            {
                if($last_next == 'last')
                {
                    $time_sql ="select train_flow_time from t_train_flow where train_flow_time<$now_time GROUP BY train_flow_time desc";
                }
                else
                {
                    $time_sql ="select train_flow_time from t_train_flow where train_flow_time>$now_time GROUP BY train_flow_time asc";
                }
                $time_id = $this->db->query($time_sql)->row_array();
                $time = $time_id['train_flow_time'];
                $time =strtotime($time);
            }
        }
        $now = date("Ymd",$time);//查询时间条件
        //先查出北京站的ID。然后查询列车流水在查询时间段内始发站ID，终点站ID包含北京站ID的数据
        // $begin_time = strtotime(date('Y-m-d', time()));
        //允许查看当前时间前一个小时到之后12小时的列车流水
        $begin_time = strtotime($now);//查询开始时间
        $end_time = $begin_time+86399;//查询结束时间
//        $station_sql = "select station_id from t_station where station_name='北京站'";//获取北京站ID，判断是终点站还是始发站，接车作业还是发车作业
        $station_sql = "select station_id from t_station where station_name='北京'";//获取北京站ID，判断是终点站还是始发站，接车作业还是发车作业
        $station_id = $this->db->query($station_sql)->row_array();
        $station_id = $station_id['station_id'];//北京站ID
        $sql = "SELECT f.is_open,tr.train_begin_station_id,tr.train_end_station_id,f.train_flow_id, f.train_number, f.actualBJtime AS planBJtime,
                    f.train_flow_statu,
                    f.is_open AS isStart,
                    IFNULL(sum(t.task_status < 6), 0) AS unfinishNum,
                    MAX(is_sound) AS isSound
                    FROM t_train_flow f LEFT JOIN t_train_task t ON f.train_flow_id = t.flow_id 
                    LEFT JOIN t_train tr ON f.train_id=tr.train_id 
                    WHERE f.train_status = 1 AND f.actualBJtime > $begin_time AND f.actualBJtime < $end_time $where 
                    GROUP BY f.train_flow_id ORDER BY f.actualBJtime, f.train_flow_id";

        $list = $this->db->query($sql)->result_array();
        $isNowJoin = false;
        $isSound = 0;
        $new_list = array();
        $i = 0;
        foreach($list as $k=>$v){
            //判断是否过期，过期修改train_flow表
            if($v['planBJtime']<time() && $v['is_open'] == 0)
            {
                $v['train_flow_statu']=1;
                //过期处理
                $flows .= "{$v['train_flow_id']},";
            }
            if($v['train_begin_station_id'] == $station_id)
            {
                $v['begin'] = true;//发车
            }
            else
            {
                $v['begin'] = false;//接车
            }
            //判断是始发站还是终点站，从而判断是接车作业还是发车作业
            $v['isWarn'] = 0;
            //未到进站或出发时间
            if($v['planBJtime'] >= $time){
                if(!$isNowJoin){
                    $isNowJoin = true;
                    $new_list[$i] = date('H:i', $time);
                    $i++;
                }

                //任务已触发
                if($v['isStart']){
                    if($v['unfinishNum'] == 0){
                        $v['color'] = "#0070c0";
                        $v['status'] = 4; //完成作业
                    }else{
                        $v['color'] = "#00ff00";
                        $v['status'] = 2; //正在进行
                    }
                }else{
                    // if($v['isTrafficTask']){
                    $v['status'] = 1; //开始作业
                    // }else{
                    // 	$v['status'] = 3; //等待作业
                    // }

                    $diff_time = $v['planBJtime'] - $time;

                    /**白色表示当前时间
                     * 红色表示该车次距发车时间不到3分钟；
                     * 绿色表示该车次任务已开始，正在进行中；
                     * 灰色表示该车次还未开始作业
                     */
                    if($diff_time < 180){
                        $v['color'] = "#ff0000";
                    }else{
                        $v['color'] = "#d8d8d8";
                    }
                }
                $v['planBJtime'] = ($v['planBJtime'] >= $time + 86400) ? '明天'.date('H:i', $v['planBJtime']) : date('H:i', $v['planBJtime']);
                $new_list[$i] = $v;
            }else{
                //任务已触发
                if($v['isStart']){
                    if($v['unfinishNum'] == 0){
                        $v['color'] = "#0070c0";
                        $v['status'] = 4; //完成作业
                    }else{
                        $v['isWarn'] = 1; //超时任务未完成提醒
                        $v['color'] = "#00ff00";
                        $v['status'] = 2; //正在进行
                    }
                }else{
                    $v['isWarn'] = 1; //超时任务未开始提醒
                    // if($v['isTrafficTask']){
                    $v['status'] = 1; //开始作业
                    // }else{
                    // 	$v['status'] = 3; //等待作业
                    // }

                    $diff_time = $v['planBJtime'] - $time;
                    $v['color'] = "#d8d8d8";
                }

                $v['planBJtime'] = date('H:i', $v['planBJtime']);
                $new_list[$i] = $v;
            }

            if($v['isSound'] > 0){
                $isSound = 1;
            }

            $i++;
        }

        $flows = rtrim($flows, ',');
        if(!empty($flows))
        {
            //对已过期车次进行修改状态为过期
            $upsql ="update t_train_flow set train_flow_statu=1 where train_flow_id IN({$flows}) ";
            $this->db->query($upsql);
        }
        if(!$isNowJoin){
            $new_list[] = date('H:i', $time);
        }
        //isSound 广播提醒
        exit(json_encode(array('code'=>0,'data'=>array('d'=>$new_list, 'y'=>date('Y', $time), 'm'=>date('m月d日', $time), 'isSound'=>$isSound),'info'=>'成功')));
    }

    /**
     * 开始作业任务
     */
    public function triggerTask(){
        /*
         1:判断是否属于可发车状态（开始作业任务的车次必须大于当前时间并且不能大于当天时间，未发车，未过期状态）
         2:成功开始作业任务后修改作业任务状态，并且推送作业任务（作业人员直接推送到人，作业岗位，登岗后再推送）
         3:当前作业任务中的任何任务只要被一个人接收，其他相同的任务必须全部撤回（删除）
         */
        //判断用户是否有操作的权限
//        if(!$this->getAuth($this->pid)){
//            exit(json_encode(array('s'=>2, 'm'=>'您还不是广播员，无权访问！')));
//        }

        $flowid = (int)$this->input->post('flowid');
        $time = time();
        $tomorrow = strtotime(date("Y-m-d",$time+86400));//截止开始作业日期

        $sql3 ="SELECT t.post_id,p.grid_id,t.task_style,t.post_type_id,f.train_begin_time,f.train_end_time,f.train_work_id, t.*,f.platform_id as Berth 
				FROM `t_train_task` t 
				LEFT JOIN t_train_flow f ON f.train_flow_id = t.flow_id 
				LEFT JOIN t_platform p ON f.platform_id=p.platform_id
				LEFT JOIN t_track m ON f.track_id = m.track_id
				WHERE f.train_status=1 and t.task_status =1 AND f.train_flow_id = {$flowid} AND f.train_flow_statu<>1 AND f.is_open=0";
        //判断条件要更改，发车车次大于当前时间不能大于当天时间，未发车未过期状态
        $taskres = $this->db->query($sql3)->result_array();
        if(!empty($taskres)){
            foreach ($taskres as $key => $value) {
                $status =3;
                //当当前的时间超过了当前车次的接车或发车时间时，按钮置灰且不可点击
                if($time <= $value['train_begin_time'] || $time <= $value['train_end_time'])
//                if(true)
                {
                    //判断作业岗位还是作业人员
                    //是否监控
                    if($value['post_type_id']==1){
                        //作业人员
                        $sql ="select post_user,post_grid from t_post where post_type_id=1 AND post_id IN($value[post_id])";
                        $res = $this->db->query($sql)->result_array();
                        $post_id = $value['post_id'];
                        foreach ($res as $kk=>$vv)
                        {
                            $users = explode(',',$vv['post_user']);//人员ID
                            $post_grid = explode(',',$vv['post_grid']);//责任网格ID

                            //判断是否跟站台有关【【【【【【start】】】】】】
                            $is_true = false;
                            if($value['task_style'] == 1)//1与站台关联  2与站台不关联
                            {
                                foreach ($post_grid as $key1=>$value1)
                                {
                                    if($value1 == $value['grid_id'])//列车所属站台
                                    {
                                        $is_true = true;
                                        break;
                                    }
                                }
                            }
                            if($is_true)
                            {
                                if(!empty($users)){
                                    $status =4;
                                    foreach ($users as $k => $v) {
                                        //将任务推到个人
                                        $usql ="insert into t_train_task_sub(task_id,accepitid,receive_user_id,receive_time,work_status)VALUES({$value['task_id']},{$v},'{$v}',{$time},0)";
                                        $insert = $this->db->query($usql);
//                                $send = $this->sendmess('admin',$value['content'],$v['LoginName'],$value['title'],$url,$type);
                                    }
                                }
                            }
                        }
                        if(empty($post_id)||$post_id=="")
                        {
                            $post_id = '0';
                        }
                        //判断是否跟站台有关【【【【【【end】】】】】】
                    }else{
                        //作业岗位
                        $sql ="select post_id,post_user,post_grid from t_post where post_type_id=2 AND post_id IN ($value[post_id])";
                        $res = $this->db->query($sql)->result_array();
                        $post_id = "";
                        foreach ($res as $kk=>$vv)
                        {
//                        $users = $res['post_user'];//岗位ID
                        $post_grid = explode(',',$vv['post_grid']);//责任网格ID

                            //判断是否跟站台有关【【【【【【start】】】】】】
                            $is_true = false;
                            if($value['task_style'] == 1)//1与站台关联  2与站台不关联
                            {
                                foreach ($post_grid as $key1=>$value1)
                                {
                                    if($value1 == $value['grid_id'])//列车所属站台
                                    {
                                        //拼接新的岗位id到tsk表
                                        $post_id = "{$vv['post_id']},";
                                        $is_true = true;
                                        break;
                                    }
                                }
                            }
                            //判断是否跟站台有关【【【【【【end】】】】】】

                            if($is_true)
                            {
                                    $status =4;
//                            foreach ($users as $k => $v) {
                                    //将任务推到岗位
                                    //判断在岗的人员
                                    $post_sql = "select user_id from t_user where is_online=1 AND post_id IN($vv[post_id])";
                                    $post_user = $this->db->query($post_sql)->result_array();
                                    if(!empty($post_user))
                                    {
                                        $string = "";
                                        foreach ($post_user as $kkk=>$vvv)
                                        {
                                            $string .= "({$value['task_id']},{$vvv['user_id']},'{$vvv['user_id']}',{$time},0),";
                                        }
                                        $string = rtrim($string, ',');
                                        if(!empty($string))
                                        {
                                            //然后推送到个人
                                            $usql ="insert into t_train_task_sub(task_id,accepitid,receive_user_id,receive_time,work_status)VALUES{$string}";
                                            $insert = $this->db->query($usql);
//                                      //$send = $this->sendmess('admin',$value['content'],$v['LoginName'],$value['title'],$url,$type);

                                        }
                                    }
//                            }
                            }
                        }
                        $post_id = rtrim($post_id, ',');
                        if(empty($post_id)||$post_id=="")
                        {
                            $post_id = '0';
                        }
                    }
//                    if($value['tasktype']==1){//通知
//                        $url ="/plugins/trainnotice/index";
//                        $type="trainnotice";
//                    }else{
//                        $url ="/plugins/traintask/index";
//                        $type="traintask";
//                    }
                    $status =4;

                    //修改任务状态d
//                    $upsql ="update t_train_task set post_id='{$post_id}',task_status={$status},up_time={$time} where task_id={$value['task_id']} ";
                    $upsql ="update t_train_task set task_status={$status},up_time={$time} where task_id={$value['task_id']} ";
                    $this->db->query($upsql);
                }
                else
                {
                    exit(json_encode(array('code'=>1,'data'=>'','info'=>'现在不能开始作业')));
                }
            }

        }else{
            exit(json_encode(array('code'=>1,'data'=>'','info'=>'任务未就绪')));
        }

        //修改列车的触发状态
        $sql="update t_train_flow set is_open =1,train_trigger_time={$time} where train_flow_id = {$flowid}";
        $this->db->query($sql);
        exit(json_encode(array('code'=>0,'data'=>'','info'=>'触发成功')));
    }

    /**
     * 获取右侧任务流程(等同编辑车次)
     */
    public function getTrainTaskFlow(){
        /*
         1:根据列车流水ID获取详细信息（编辑同用）
         */
        $flowid = (int)$this->input->post('flowid');
        $update = (int)$this->input->post('update');
        $train_status = "AND f.train_status = 1";
        if($update==1)
        {
            $train_status = "";
        }
        if(empty($flowid))
        {
            exit(json_encode(array('code'=>1,'data'=>'','info'=>'流水不能为空')));
        }
        $time = time();
        $sql = "SELECT f.actualBJtime,f.is_open,f.train_flow_statu,f.train_status,f.is_beinglate,f.beinglate_time,s.station_id as train_begin_station_id,ss.station_id as train_end_station_id,sta.platform_name,tr.track_name,tra.track_name update_track_name,f.train_begin_time,f.train_end_time,s.station_name train_begin_station_name,ss.station_name train_end_station_name,f.track_id,f.update_track_id,f.platform_id,f.train_flow_id,f.train_work_id, f.train_number 
                FROM t_train_flow f LEFT JOIN t_train t ON f.train_id=t.train_id 
                LEFT JOIN t_station s ON t.train_begin_station_id=s.station_id 
                LEFT JOIN t_station ss ON t.train_end_station_id=ss.station_id 
                LEFT JOIN t_track tr ON f.track_id=tr.track_id
                LEFT JOIN t_track tra ON f.update_track_id=tra.track_id
                LEFT JOIN t_platform sta ON f.platform_id=sta.platform_id
                WHERE f.train_flow_id = {$flowid} {$train_status}";
        $flowInfo = $this->db->query($sql)->row_array();
        $flowInfo['train_begin_time'] = date('H:i',$flowInfo['train_begin_time']);
        $flowInfo['train_end_time'] = date('H:i',$flowInfo['train_end_time']);
        if($update==1)
        {
            exit(json_encode(array('code'=>0,'data'=>$flowInfo,'info'=>'成功')));
        }
        if(empty($flowInfo)){
            exit(json_encode(array('code'=>1,'data'=>'','info'=>'流水不存在或已过期')));
        }
        if($flowInfo['train_flow_statu']==1 || $flowInfo['is_open']==1 || $flowInfo['train_status']==2 || $time >= $flowInfo['actualBJtime'] || (date('Ymd',$flowInfo['actualBJtime']) != date('Ymd',$time)))
        {
            $flowInfo['is_start'] =false;
        }
        else
        {
            $flowInfo['is_start'] =true;
        }

        $sql = "SELECT IFNULL(sum(t.task_status < 6), 0) AS unfinishNum,ts.receive_time,ts.done_time,t.flow_id,flow.train_number,flow.train_begin_time,flow.train_end_time,u.user_name,t.task_id, t.task_info_id, t.task_name, t.task_type, t.task_status, t.post_id, w.post_id AS wid, w.post_type_id AS wtype, w.post_name AS wname, t.pid AS fid, t.code_pid, t.code_id, IFNULL(t.up_time, 0) uptime, ts.accepitid, ts.receive_user_id, ts.pub_time, ts.work_status 
                FROM t_train_task t LEFT JOIN t_train_flow flow ON t.flow_id=flow.train_flow_id
                LEFT JOIN t_train train ON flow.train_id=train.train_id 
                LEFT JOIN t_post w ON t.post_id = w.post_id 
                LEFT JOIN t_train_task_sub ts ON t.task_id = ts.task_id 
                LEFT JOIN t_user u ON u.user_id=ts.receive_user_id AND ts.work_status > 0 WHERE t.flow_id = {$flowid} GROUP BY t.task_id ORDER BY t.task_id,ts.work_status";
        $list = $this->db->query($sql)->result_array();
        $i = 0;
        foreach ($list as $k=>$v)
        {
            if($v['unfinishNum'] == 0)
            {
                $i++;
            }
            //任务还未触发
            if($v['uptime'] <= 0 || $v['uptime'] > $time){
                if($v['task_status'] == 0){
                    $staStr = '未下发任务';
                    $color = '#e6e6e6'; //灰色
                }elseif($v['task_status'] == 2){
                    $staStr = '已取消';
                    $color = '#e6e6e6'; //灰色
                }else{
                    $staStr = '未发布';
                    $color = '#e6e6e6'; //灰色
                }
            }else{
                //任务触发后3分钟内
                $diff_time = $time - $v['uptime'];
                if($diff_time <= 180){
                    if($v['task_status'] < 5){
                        $staStr = '未接受';
                        $color = '#ec5869'; //红色
                    }elseif($v['task_status'] == 5){
                        $staStr = '进行中';
                        $color = '#58ec9e'; //绿色
                        //脱岗注释start
                        /*
                        //脱岗10秒以上
                        if($v['task_type']==0){
                            if($v['wtype']==1){
                                if($v['aid']==1){//作业岗位是站台区
                                    $work = $flowInfo['Berth'];
                                }else{//作业岗位是候车区
                                    $work = $flowInfo['workid'];
                                }
                                $sql = "SELECT p.status, p.leavetime FROM t_bjnz_post p LEFT JOIN t_user u ON u.PID =p.pid
										WHERE p.wid ={$v['wid']} and p.pid = {$v['accepitid']} and FIND_IN_SET({$work},p.mid)";
                                $post_info = $this->db->query($sql)->fetch();

                                if($post_info['status'] == 0 && time()-$post_info['leavetime'] > 10){
                                    $tagColor = '#ffff00'; //黄
                                }
                            }
                        }
                        */
                        //脱岗注释end
                    }elseif($v['task_status'] == 6){
                        $staStr = '已完成';
                        $color = '#40abf7'; //蓝色
                    }

                }else{
                    if($v['task_status'] < 5){
                        $is_sound = true;
                        $staStr = '未接受';
                        $color = '#ec5869'; //红
                    }elseif($v['task_status'] == 5){
                        $staStr = '进行中';
                        $color = '#58ec9e'; //绿色

                    //脱岗注释start
                        /*
                        //脱岗10秒以上, 脱岗180秒以上
                        if($v['task_type']==0){ //作业任务
                            if($v['wtype']==1){ //作业岗位
                                if($v['aid']==1){//作业岗位是站台区
                                    $work = $flowInfo['Berth'];
                                }else{//作业岗位是候车区
                                    $work = $flowInfo['workid'];
                                }
                                $sql = "SELECT p.status, p.leavetime FROM t_bjnz_post p LEFT JOIN t_user u ON u.PID =p.pid
										WHERE p.wid ={$v['wid']} and p.pid = {$v['accepitid']} and FIND_IN_SET({$work},p.mid)";
                                $post_info = $this->db->query($sql)->fetch();
                                if($post_info['status'] == 0){
                                    $leave_diff = time()-$post_info['leavetime'];
                                    if($leave_diff > 10){
                                        $tagColor = '#ffff00'; //黄
                                    }
                                    if($leave_diff > 180){
                                        $tagColor = '#ff0000'; //红
                                        $is_sound = true;
                                    }
                                }
                            }
                        }
                        */
                    //脱岗注释end
                    }elseif($v['task_status'] == 6){
                        $staStr = '已完成';
                        $color = '#40abf7'; //蓝色
                    }
                }
            }
            $list[$k]['stastr'] = $staStr;
            $list[$k]['color'] = $color;
            $list[$k]['user_name'] = $v['user_name'] != ''?$v['user_name']:'无';
            $list[$k]['train_begin_time'] = empty($v['train_begin_time'])?'':date('Y-m-d H:i:s',$v['train_begin_time']);
            $list[$k]['train_end_time'] = empty($v['train_end_time'])?'':date('Y-m-d H:i:s',$v['train_end_time']);
            $list[$k]['receive_time'] = empty($v['receive_time'])?'':date('Y-m-d H:i:s',$v['receive_time']);
            $list[$k]['done_time'] = empty($v['done_time'])?'':date('Y-m-d H:i:s',$v['done_time']);
        }
        if(($i == count($list) && $flowInfo['is_open']==1) || ($flowInfo['train_flow_statu']==1 && $flowInfo['is_open']==0) || ($flowInfo['train_flow_statu']!=1 && $flowInfo['is_open']==0))
        {
            //任务全部已完成 或者过期
            $flowInfo['is_done']=true;
        }
        else
        {
            $flowInfo['is_done']=false;
        }
        if($flowInfo['update_track_id'] > 0)
        {
            //如有修改股道则赋值到原股道
            $flowInfo['track_id'] = $flowInfo['update_track_id'];
            $flowInfo['track_name'] = $flowInfo['update_track_name'];
        }
        exit(json_encode(array('code'=>0,'data'=>array('result'=>$flowInfo,'list'=>$list),'info'=>'成功')));

//无用注释start
/*
        $flow = array();
        $level = 1;
        $task_level = array(); //记录任务对应的级别
        $draw_arr = array(); // 存放绘图数据
        foreach($list as $k=>$v){
            if($v['codepid'] == 0){
                //记录同一级任务的数量
                if(isset(self::$width_num[$level])){
                    self::$width_num[$level]++;
                }else{
                    self::$width_num[$level] = 1;
                }
                $task_level[$v['codeid']] = $level;
                $flow[$level][$v['codeid']] = array('id'=>$v['codeid'], 'tname'=>$v['tname'], 'wname'=>$v['wname'], 'aname'=>$v['aname'], 'status'=>$v['status'], 'uptime'=>$v['uptime'], 'pubtime'=>$v['pubtime'], 'workstatus'=>$v['workstatus'], 'wid'=>$v['wid'], 'wtype'=>$v['wtype'], 'aid'=>$v['aid'], 'accepitid'=>$v['accepitid'], 'tasktype'=>$v['task_type']);
                $flow[$level][$v['codeid']]['parent_list'][] = array('parent_xnum'=>1, 'parent_ynum'=>$level-1);
                $num = count($flow[$level]);
                $this->getLevelTask($list, $flow, $level, $v['codeid'], $num, $task_level, $flowInfo);
            }
        }

        $max_width_num = max(self::$width_num); //列表里同一级别最大任务数
        // $max_width_num = $max_width_num >= 5 ? $max_width_num : 5; //一排最少5个任务宽度
        $max_width = self::TASK_WIDTH*$max_width_num + ($max_width_num-1)*self::MARGIN_RIGHT;
        $max_width = $max_width < 540 ? 540 : $max_width;
        $draw_arr = array();
        $is_sound = false;
        $time = time();
        foreach($flow as $lev=>$val){
            $i = 1; //当前是这一级别的第几个
            foreach($val as $k=>$v){
                $level_num = self::$width_num[$lev]; //当前级别任务总数
                //任务图起点坐标
                $start_x = ($max_width - $level_num*self::TASK_WIDTH - ($level_num-1)*self::MARGIN_RIGHT)/2 + ($i*self::TASK_WIDTH + ($i-1)*self::MARGIN_RIGHT - self::TASK_WIDTH);
                $start_y = ($lev-1)*self::TASK_HEIGHT + $lev*self::LINE_HEIGHT;

                //加入画任务图数组
                $v['tname'] = !empty($v['tname']) ? $v['tname'] : '';
                $v['wname'] = !empty($v['wname']) ? $v['wname'] : '';
                $v['uptime'] = !empty($v['uptime']) ? $v['uptime'] : 0;
                $v['status'] = !empty($v['status']) ? $v['status'] : 0;
                $task_name = $v['tname'] . (!empty($v['aname']) ? '-'.$v['aname'] : '-'.$v['wname']);
                $staStr = '';
                $color = '#fff';
                $tagColor = ''; //脱岗三角提醒色
                //任务还未触发
                if($v['uptime'] <= 0 || $v['uptime'] > $time){
                    if($v['status'] == 0){
                        $staStr = '未确认';
                        $color = '#d8d8d8'; //灰色
                    }elseif($v['status'] == 2){
                        $staStr = '已取消';
                        $color = '#d8d8d8'; //灰色
                    }else{
                        $staStr = '未发布';
                        $color = '#d8d8d8'; //灰色
                    }
                }else{
                    //任务触发后3分钟内
                    $diff_time = $time - $v['uptime'];
                    if($diff_time <= 180){
                        if($v['status'] < 5){
                            $staStr = '未接受';
                            $color = '#ffff00'; //黄色
                        }elseif($v['status'] == 5){
                            $staStr = '进行中';
                            $color = '#00ff00'; //绿色
                            //脱岗10秒以上
                            if($v['task_type']==0){
                                if($v['wtype']==1){
                                    if($v['aid']==1){//作业岗位是站台区
                                        $work = $flowInfo['Berth'];
                                    }else{//作业岗位是候车区
                                        $work = $flowInfo['workid'];
                                    }
                                    $sql = "SELECT p.status, p.leavetime FROM t_bjnz_post p LEFT JOIN t_user u ON u.PID =p.pid
										WHERE p.wid ={$v['wid']} and p.pid = {$v['accepitid']} and FIND_IN_SET({$work},p.mid)";
                                    $post_info = $this->db->query($sql)->fetch();

                                    if($post_info['status'] == 0 && time()-$post_info['leavetime'] > 10){
                                        $tagColor = '#ffff00'; //黄
                                    }
                                }
                            }
                        }elseif($v['status'] == 6){
                            $staStr = '已完成';
                            $color = '#0070c0'; //蓝色
                        }

                    }else{
                        if($v['status'] < 5){
                            $is_sound = true;
                            $staStr = '未接受';
                            $color = '#ff0000'; //红
                        }elseif($v['status'] == 5){
                            $staStr = '进行中';
                            $color = '#00ff00'; //绿色
                            //脱岗10秒以上, 脱岗180秒以上
                            if($v['task_type']==0){ //作业任务
                                if($v['wtype']==1){ //作业岗位
                                    if($v['aid']==1){//作业岗位是站台区
                                        $work = $flowInfo['Berth'];
                                    }else{//作业岗位是候车区
                                        $work = $flowInfo['workid'];
                                    }
                                    $sql = "SELECT p.status, p.leavetime FROM t_bjnz_post p LEFT JOIN t_user u ON u.PID =p.pid
										WHERE p.wid ={$v['wid']} and p.pid = {$v['accepitid']} and FIND_IN_SET({$work},p.mid)";
                                    $post_info = $this->db->query($sql)->fetch();
                                    if($post_info['status'] == 0){
                                        $leave_diff = time()-$post_info['leavetime'];
                                        if($leave_diff > 10){
                                            $tagColor = '#ffff00'; //黄
                                        }
                                        if($leave_diff > 180){
                                            $tagColor = '#ff0000'; //红
                                            $is_sound = true;
                                        }
                                    }
                                }
                            }
                        }elseif($v['status'] == 6){
                            $staStr = '已完成';
                            $color = '#0070c0'; //蓝色
                        }

                        //任务还没推 脱岗
                        // if(empty($v['aname'])){
                        // 	$tagColor = '#ff0000'; //红
                        // }
                    }
                }

                $draw_arr[] = array('task', $start_x, $start_y, self::TASK_WIDTH, self::TASK_HEIGHT, self::MARGIN_RIGHT, $task_name, $staStr, $color, $tagColor);

                foreach($v['parent_list'] as $val){
                    $p_level_num = self::$width_num[$val['parent_ynum']]; //父级任务总数
                    //父任务连线起点坐标
                    $begin_x = ($max_width - $p_level_num*self::TASK_WIDTH - ($p_level_num-1)*self::MARGIN_RIGHT)/2 + ($val['parent_xnum']*self::TASK_WIDTH + ($val['parent_xnum']-1)*self::MARGIN_RIGHT - self::TASK_WIDTH/2);
                    $begin_y = $val['parent_ynum']*(self::TASK_HEIGHT + self::LINE_HEIGHT);

                    //当前任务连线终点坐标
                    $end_x = ($max_width - $level_num*self::TASK_WIDTH - ($level_num-1)*self::MARGIN_RIGHT)/2 + ($i*self::TASK_WIDTH + ($i-1)*self::MARGIN_RIGHT - self::TASK_WIDTH/2);
                    $end_y = ($lev-1)*self::TASK_HEIGHT + $lev*self::LINE_HEIGHT;

                    //加入划线数组
                    $draw_arr[] = array('line', $begin_x, $begin_y, $end_x, $end_y-2);
                }

                $i++;
            }
        }

        $title = $flowInfo['TrainName'] . ($flowInfo['goShuttle'] == 2 ? '发车作业' : ($flowInfo['reachShuttle'] == 2 ? '接车作业' : '作业流程'));
        $max_height = self::$height_num * (self::TASK_HEIGHT + self::LINE_HEIGHT) + self::MARGIN_RIGHT;
        $max_height = $max_height < 500 ? 500 : $max_height;

        $is_sound = !$this->getAuth($this->pid) ? false : $is_sound;
        exit(json_encode(array('s'=>0, 'm'=>'', 'd'=>$draw_arr, 'w'=>$max_width, 'h'=>$max_height, 'title'=>$title, 'is_sound'=>$is_sound)));
        */
//无用注释end
    }

    /**
     * 添加临时车次(暂时不做)
     */
    public function AddTrainTaskFlow()
    {
        /*
         1:增加临时车次发车时间必须是当天时间，并且大于当前时间
         2:临时添加或修改车次不影响正常的车次信息
         3:临时车次必须在正常车次之外、只在当天有效
         */
        return ;
    }
    /**
     * 修改车次信息
     */
    public function UpdateTrainTaskFlow()
    {
        /*
         * 【【【【【增加日志】】】】】
         1:修改车次信息发车时间必须是当天时间，并且大于当前时间
         2:临时添加或修改车次不影响正常的车次信息
         3:修改车次必须在正常车次之外、只在当天有效
         */
        $flowid = getParam($this->input->get_post("flowid", true), 'int',0);//列车流水
//        $_message['train_id'] = getParam($this->input->get_post("trainname", true), 'string','');//车次
        $_message['train_begin_station_id'] = getParam($this->input->get_post("beginname", true), 'string','');//始发站
        $_message['train_end_station_id'] = getParam($this->input->get_post("endname", true), 'string','');//终点站
        $_message['train_begin_time'] = getParam($this->input->get_post("begintime", true), 'string','');//始发时间
        $_message['train_end_time'] = getParam($this->input->get_post("endtime", true), 'string','');//到达时间
        $_message['update_track_id'] = getParam($this->input->get_post("trackid", true), 'string','');//股道id
        $_message['platform_id'] = getParam($this->input->get_post("platformid", true), 'string','');//站台id
        $_message['train_status'] = getParam($this->input->get_post("trainstatus", true), 'string','');//停运状态1正常2停运
        $_message['is_beinglate'] = getParam($this->input->get_post("isbeinglate", true), 'int',0);//是否晚点0不晚点 1晚点
        $_message['beinglate_time'] = getParam($this->input->get_post("beinglatetime", true), 'int',0);//晚点时间 天 分 时 时间戳

        foreach ($_message as $value)
        {
            if($value == "" && $value !=0)
            {
                exit(json_encode(array('code'=>1,'data'=>'参数不全','info'=>'失败')));
            }
        }
        //判断是始发站还是终点站 始发站修改始发时间  终点站修改终点时间
        $time = time();
        $sql = "select planBJtime,train_begin_time,train_end_time from t_train_flow where train_flow_id={$flowid} and is_open=0 and train_flow_statu<>1 and train_status=1";
        $planBJtime = $this->db->query($sql)->row_array();
        if(empty($planBJtime))
        {
            exit(json_encode(array('code'=>1,'data'=>'不可以修改车次信息','info'=>'失败')));
        }
//        $station_sql = "select station_id from t_station where station_name='北京站'";//获取北京站ID，判断是终点站还是始发站，接车作业还是发车作业
        $station_sql = "select station_id from t_station where station_name='北京'";//获取北京站ID，判断是终点站还是始发站，接车作业还是发车作业
        $station_id = $this->db->query($station_sql)->row_array();
        $station_id = $station_id['station_id'];//北京站ID
        $timea = date("Ymd",$planBJtime['train_begin_time']);
        $timeb = date("Ymd",$planBJtime['train_end_time']);
        $_message['train_begin_time'] = strtotime($timea.$_message['train_begin_time']);
        $_message['train_end_time'] = strtotime($timeb.$_message['train_end_time']);
        if($_message['is_beinglate'] == 1)
        {
            $_message['actualBJtime'] = $_message['train_end_time']+$_message['beinglate_time'];
            $_message['planBJtime'] = $_message['train_end_time']+$_message['beinglate_time'];
            $_message['train_end_time'] = $_message['train_end_time']+$_message['beinglate_time'];
            $_message['train_flow_time'] = date('Ymd',$_message['planBJtime']);
        }
        else
        {
            if($_message['train_begin_station_id']==$station_id)//始发站
            {
                $_message['actualBJtime'] = $_message['train_begin_time'];
                $_message['planBJtime'] = $_message['train_begin_time'];
            }
            else//终点站
            {
                $_message['actualBJtime'] = $_message['train_end_time'];
                $_message['planBJtime'] = $_message['train_end_time'];
            }
        }
//        if((date('Ymd',$time) == date('Ymd',$planBJtime['planBJtime'])) && $planBJtime['planBJtime']>$time)
        if($planBJtime['planBJtime']>$time)
        {
            //可以修改车次信息
            $res = $this->M_train_flow->updateData($_message,array('train_flow_id'=>$flowid));
            if($res)
            {
                exit(json_encode(array('code'=>0,'data'=>'','info'=>'成功')));
            }
            else
            {
                exit(json_encode(array('code'=>1,'data'=>'修改失败','info'=>'修改失败')));
            }
        }
        else
        {
            //不可以修改车次信息
            exit(json_encode(array('code'=>1,'data'=>'不可以修改车次信息','info'=>'失败')));
        }
    }
    /**
     * 生成列车流水脚本任务（后期放到脚本文件中）
     */
    public function doTrainFlow()
    {
        /*
         * 【【【【【【注意判断，如果已经生成明天的信息，则不重新生成,要增加日志】未完成】】】】】
         1:当天生成第二天的列车流水信息
         2:临时添加或修改车次不影响正常的车次信息
         3:临时车次必须在正常车次之外、只在当天有效
         */
        $createtime = time();//创建时间
        $tomorrow = strtotime(date("Y-m-d",$createtime+86400));//明天
//        $createtime = time()-86400;//今天测试
//        $tomorrow = strtotime(date("Y-m-d",$createtime));//今天测试用

        //需要生成流水的列车

        //1.检查列车是否停运，是否在有效期

//        $sql = "select f.train_flow_id from t_train_flow f left join t_train_task t on f.train_flow_id=t.flow_id where f.train_flow_id='33350' GROUP BY f.train_flow_id";
//
//        $train = $this->db->query($sql)->result_array();
//        $sql = "delete from t_train_flow where train_flow_id='33350'";
//        $this->db->query($sql);
//        $i = 0;
//        foreach ($train as $key=>$value)
//        {
//            $sql = "delete from t_train_task where flow_id={$value['train_flow_id']}";
//            $this->db->query($sql);
//            $i++;
//        }
//        echo $i;
//        exit;
        $sql = "SELECT * FROM t_train WHERE start_time <= $tomorrow AND finsh_time >= $tomorrow AND train_status=1";
        $train = $this->db->query($sql)->result_array();
        //2.循环判断发车周期
        //循环生成所需参数
        $string = '';
        foreach($train as $k=>$v) {
            if($v['train_depart_cycle'] == 2)//隔天
            {
                $start_time = strtotime(date('Y-m-d',$v['start_time']));
                $n = ($tomorrow-$start_time)/86400;
                if($n%2!=0 || $n ==0)//不是隔天跳过
                {
                    continue;
                }
            }
            elseif($v['train_depart_cycle'] == 3)//每周
            {
                $v['train_depart_week'] = explode(',',$v['train_depart_week']);
                $dd = date('w',$tomorrow);//生成日期是周几
                $s =false;
                foreach($v['train_depart_week'] as $kk=>$vv)
                {
                    if($vv == $dd)
                    {
                        $s=true;
                        break;
                    }
                }
                if(!$s)
                {
                    continue;
                }
            }
            elseif($v['train_depart_cycle'] == 4)//开一停二
            {
                $start_time = strtotime(date('Y-m-d',$v['start_time']));
                $n = ($tomorrow-$start_time)/86400+1;
                if($n%3!=1)
                {
                    continue;
                }
            }
            elseif($v['train_depart_cycle'] == 5)//开二停一
            {
                $start_time = strtotime(date('Y-m-d',$v['start_time']));
                $n = ($tomorrow-$start_time)/86400+1;
                if($n%3==0)
                {
                    continue;
                }
            }
            $v['train_flow_statu'] = "3";
            $v['update_track_id'] = "0";
            $v['track_name'] = "股道名";//以后需要，可在t_train表增加股道名字段
            $v['platform_name'] = "站台名";//以后需要，可在t_train表增加站台名字段
            $v['train_trigger_time'] = "0";
            $v['is_open'] = "0";
            $v['train_begin_time'] = strtotime(date("His",$v['train_begin_time'])) +86400;
            $v['train_end_time'] = strtotime(date("His",$v['train_end_time'])) +86400;
            $v['train_in_time'] = strtotime(date("His",$v['train_in_time'])) +86400;
            $v['train_out_time'] = strtotime(date("His",$v['train_out_time'])) +86400;

            //计算是终点站还是始发站，再判断途径时间（始发站为发车时间，终点站为到达时间）
            $station_sql = "select station_id from t_station where station_name='北京站'";//获取北京站ID，判断是终点站还是始发站，接车作业还是发车作业
            $station_id = $this->db->query($station_sql)->row_array();
            if($station_id['station_id'] == $v['train_begin_station_id'])
            {
                //始发站，发车
                $v['planBJtime'] = $v['train_begin_time'];
                $v['actualBJtime'] = $v['train_begin_time'];
            }
            else
            {
                //终点站，接车
                $v['planBJtime'] = $v['train_end_time'];
                $v['actualBJtime'] = $v['train_end_time'];
            }

            $v['train_flow_addtime'] = $createtime;
            $v['train_flow_time'] = date("Ymd",$createtime+86400);
            $string .= $this->getSqlString($v);
        }
        $string = rtrim($string, ',');
        if(!empty($string)){
            try
            {
                //事务开始
                $this->db->trans_begin();
                $sql = "INSERT INTO t_train_flow (train_id,train_number,train_type_id,train_style_id,`train_flow_time`,train_begin_time,train_end_time,train_in_time, train_out_time, train_trigger_time, train_ago_number,train_back_number,track_id,update_track_id,track_name,platform_id,platform_name,train_status,train_work_id,train_flow_statu,is_open,planBJtime,actualBJtime,train_flow_addtime)  VALUES {$string}";
                $res1 = $this->db->query($sql);

//                $sql = "SELECT * FROM t_train_flow WHERE train_flow_addtime = {$createtime}";
                $sql = "SELECT * FROM t_train_flow WHERE train_flow_addtime = {$createtime}";
                $list = $this->db->query($sql)->result_array();
                //print_r($list);exit;
                $string = '';
                foreach($list as $k=>$v){
                    $sql2 ="SELECT {$v['train_flow_id']} as flowid,w.job_process_detail_id,w.job_process_id,t.job_id as tid,t.job_content,t.job_type,t.`job_name`,t.post_type_id,t.is_control,t.job_post FROM t_job_process_detail w LEFT JOIN t_job t ON w.job_id = t.job_id WHERE w.job_process_id ={$v['train_work_id']}";
                    $tasklist = $this->db->query($sql2)->result_array();
                    foreach ($tasklist as $key => $val) {
                        $title =$v['train_number'].$val['job_name'].'提醒';
                        $content = $v['train_number'].$val['job_content'];
                        $string .= "({$val['job_process_detail_id']},{$val['job_process_id']},'admin','{$title}','{$val['job_name']}','{$val['job_type']}','{$val['post_type_id']}','0','broadcast','1','{$val['flowid']}','{$val['job_post']}','{$content}','{$val['job_process_detail_id']}','0','0','0','0','0'),";
                    }
                }
                $string = rtrim($string, ',');
                $sql = "INSERT INTO t_train_task ( `task_info_id`, `tid`, `user_id`, `task_title`, `task_name`, `task_style`,`post_type_id`,`task_type`,`broadcast`,`task_status`,`flow_id`,`post_id`,`task_content`,`pid`,`code_pid`,`code_id`,`is_open`,`up_time`,`is_sound`) VALUES {$string}";
                $res2 = $this->db->query($sql);

                // 新生成的流水需要添加任务到轮询表
                if($res1 && $res2)
                {
                    //事务提交
                    $this->db->trans_commit();
                }
                else
                {
                    //事务回滚
                    $this->db->trans_rollback();
                }
            }
            catch (Exception $e)
            {
                //事务回滚，并且抛出异常
                $this->db->trans_rollback();
                throw new Exception($e->getMessage());
            }
        }
        exit;
    }

    private function getSqlString($v){
        return "('{$v['train_id']}','{$v['train_number']}', '{$v['train_type_id']}', '{$v['train_style_id']}', '{$v['train_flow_time']}', '{$v['train_begin_time']}', '{$v['train_end_time']}', '{$v['train_in_time']}', '{$v['train_out_time']}', {$v['train_trigger_time']}, '{$v['train_ago_number']}', '{$v['train_back_number']}', '{$v['track_id']}','{$v['update_track_id']}','{$v['track_name']}', '{$v['platform_id']}', '{$v['platform_name']}', '{$v['train_status']}', '{$v['job_process_id']}','{$v['train_flow_statu']}','{$v['is_open']}','{$v['planBJtime']}','{$v['actualBJtime']}','{$v['train_flow_addtime']}'),";
    }
}